/*************************************************************
 * Title: 
 * Description: 
 * Author: Snow Huang
 * Email: Shaobin.Software@gmail.com Shaobin_Software@163.com
 * CreateTime: Aug 6, 2010 3:35:39 PM
 * Copyright © 落羽社区 All right reserved
 ************************************************************/
package snow.core.util.toolkit;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Random;

import snow.core.util.constants.ApplicationConstants;

/**
 * 
 */
public class ImageHelper {

	private static final char[] CODE = ApplicationConstants.VALIDATE_CODE.toCharArray();

	private static Random random = new Random();

	public static Color getRandomColor() {
		return getRandomColor(0, 255);
	}

	public static Color getRandomColor(int fc, int bc) {
		if (fc > 255) {
			fc = 255;
		}
		if (bc > 255) {
			bc = 255;
		}
		int n = Math.abs(fc - bc);
		int r = fc + random.nextInt(n);
		int g = fc + random.nextInt(n);
		int b = fc + random.nextInt(n);
		return new Color(r, g, b);
	}

	public static String getValidateCode(int length) {
		if (length < 1) {
			length = 4; // 默认长度为4
		}
		StringBuilder code = new StringBuilder(length);
		for (int i = 0; i < length; i++) {
			code.append(CODE[random.nextInt(CODE.length)]);
		}
		return code.toString();
	}

	public static BufferedImage getValidateCodeImageFrom(String code, int width, int height) {
		// 创建图像image
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = image.createGraphics();

		// 设置背景颜色
		g.setColor(new Color(255, 255, 255));
		g.fillRect(0, 0, width, height);

		// 设置字体
		g.setFont(new Font("Arial", Font.PLAIN, height - 2));

		// 设置边框
		// g.setColor(Color.BLACK);
		// g.drawRect(0, 0, width - 1, height - 1);

		// 随机生成160条干扰线
		g.setColor(getRandomColor(200, 255));
		for (int i = 0; i < 160; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(4);
			int yl = random.nextInt(4);
			g.drawLine(x, y, x + xl, y + yl);
		}

		int length = code.length();

		for (int i = 0; i < length; i++) {
			g.setColor(getRandomColor());
			g.drawString(String.valueOf(code.charAt(i)), (random.nextFloat() + 18) * i + 5, (random.nextFloat() + 3.5f) * 4);
		}

		// 使图像生效
		g.dispose();

		return image;
	}
}
